import React, { useEffect, useState } from 'react';
import { Button, Flex, Image, Modal, Select, Space, Table, Tag } from 'antd';
import type { TableColumnsType, TableProps } from 'antd';
import { studentBatch, studentDel, studentGet, StudentType } from '../../api/student';
import { useNavigate } from 'react-router-dom';

type TableRowSelection<T extends object = object> = TableProps<T>['rowSelection'];



// 测试数据包
// const dataSource = Array.from<StudentType>({ length: 4 }).map<StudentType>((_, i) => ({
//   code: i+'',
//   name: `Edward King ${i}`,
//   gender: '32',
//   stuClass: ['1班'],
//   avatar:''
// }));

const Student: React.FC = () => {
  
  const [loading, setLoading] = useState(false);
  const [dataSource,setDataSource] = useState<Array<StudentType>>([])
  const navigate = useNavigate()

  // 配置表格基本信息
  const columns: TableColumnsType<StudentType> = [
    { title: '姓名', dataIndex: 'name' },
    { title: '学号', dataIndex: 'code' },
    { title: '性别', dataIndex: 'gender' },
    { title: '班级', dataIndex: 'stuClass',render:(sclass:Array<string>)=>{
      return <Space>
                  <Tag color='warning'>{sclass[0]}</Tag>
                  <Tag color='processing'>{sclass[1]}</Tag>
                  <Tag color='success'>{sclass[2]}</Tag>
            </Space>
    } },
    { title: '头像', dataIndex: 'avatar',render:(url:string)=>{
      return <Image src={url}/>
    } },
    { title: '操作', render:(_,record)=>{
      return <Space>
                <Button type='primary' size='small' onClick={()=>{handleEdit(record)}}>
                  编辑
                </Button>
                <Button type='primary' size='small'danger onClick={()=>{showModal(record.objectId!)}}>删除</Button>
            </Space>
    } },
  ];
   //编辑
  const handleEdit = (stuObj:StudentType)=>{
    navigate('/student/edit',{
      state:stuObj
    })
  }

  useEffect(()=>{
    studentGet().then(res=>{
      console.log(res);
      setDataSource(res.data.results)
    })
  },[])
 

  //筛选查询
  const [gender,setGender] = useState('')
  const handleSearch = ()=>{
    console.log(gender);
    studentGet({gender}).then(res=>{
      setDataSource(res.data.results)
    })
  }

  //删除
  const [isModalOpen, setIsModalOpen] = useState(false);
  let [delId,setDelId] = useState('')  //存储待删除的数据id
  const showModal = (objectId:string) => {
    setDelId(objectId)
    setIsModalOpen(true);
  };

  const handleOk = () => {
    // 发起删除请求
    studentDel(delId).then(()=>{
      let dataList = dataSource.filter(item=>item.objectId!=delId) //移除本地列表数据
      setDataSource([...dataList]) 
    })
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };


  
  //表格勾选触发的事件
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]); //被选中的数据id
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection: TableRowSelection<StudentType> = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const hasSelected = selectedRowKeys.length > 0;
  // 批量删除
  const handleBatchDel = ()=>{
    studentBatch(selectedRowKeys).then(()=>{
      let dataList = dataSource.filter(item=>!selectedRowKeys.includes(item.objectId!)) //移除本地列表数据
      setDataSource([...dataList]) 
    })
  }
  

  return (
    <>
      <Flex gap="middle" vertical>
        <Flex align="center" gap="middle">
          <Button type="primary" danger onClick={handleBatchDel} disabled={!hasSelected} loading={loading}>
            批量删除
          </Button>
          {hasSelected ? `Selected ${selectedRowKeys.length} items` : null}
          <Select
            style={{ width: 120 }}
            options={[
              { value: '女', label: '女' },
              { value: '男', label: '男' },
            ]}
            onChange={(value)=>{setGender(value)}}
          />
          <Button type="primary" onClick={handleSearch}>
            查询
          </Button>
          
        </Flex>
        <Table<StudentType> 
          rowSelection={rowSelection} 
          columns={columns} 
          dataSource={dataSource} 
          rowKey="objectId"
        />
      </Flex>
      <Modal title="确定要删除吗？" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <h2>删除后，数据无法找回，请三思！</h2>
      </Modal>
    </>
  );
};

export default Student;